﻿
/***************************************************************************

Copyright (c) BizRulX. All rights reserved.

***************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio;
using System.Runtime.InteropServices;

namespace RuleXSoft.BizRuleCreator
{
    public class SelectionEvents : IVsSelectionEvents
    {
        private static IVsMonitorSelection SelectionService;

        private static uint ContextCookie = RegisterContext();

        private static uint RegisterContext()
        {
            // Initialize the selection service
            SelectionService = (IVsMonitorSelection)Package.GetGlobalService(typeof(SVsShellMonitorSelection));

            // Get a cookie for our UI Context. This “registers” our
            // UI context with the selection service so we can set it again later.

            uint retVal;
            Guid uiContext = GuidList.UICONTEXT_RulXFileSelected;

            SelectionService.GetCmdUIContextCookie(ref uiContext, out retVal);

            return retVal;
        }
        #region IVsSelectionEvents Members

        public int OnCmdUIContextChanged(uint dwCmdUICookie, int fActive)
        {
            return VSConstants.S_OK;
        }

        public int OnElementValueChanged(uint elementid, object varValueOld, object varValueNew)
        {
            return VSConstants.S_OK;
        }

        public int OnSelectionChanged(IVsHierarchy pHierOld, uint itemidOld, IVsMultiItemSelect pMISOld, ISelectionContainer pSCOld, IVsHierarchy pHierNew, uint itemidNew, IVsMultiItemSelect pMISNew, ISelectionContainer pSCNew)
        {
            if (pHierNew != null)
            {
                object fileName;
                pHierNew.GetProperty(itemidNew, (int)__VSHPROPID.VSHPROPID_Name, out fileName);

                if (fileName != null && fileName.ToString().EndsWith(".rulx"))
                {
                    // If we meet the conditions, set the UI context to be active.
                    SelectionService.SetCmdUIContext(ContextCookie, 1);

                    return VSConstants.S_OK;
                }
            }

            // Otherwise, deactivate it.
            SelectionService.SetCmdUIContext(ContextCookie, 0);

            return VSConstants.S_OK;
        }

        #endregion
    }
}
